import { _decorator, Component, Node, Button, Label, Slider, director } from 'cc';
import { CommandManager, CommandManagerState } from '../CommandManager';
import { UIManager } from './UIManager';
import { GameCore } from '../../../core/game';
import { GameConfig } from '../../../config';
import { CommandExecutor } from '../../../TestCmdExecutor';
import { TestBattleScript } from '../../../TestBattleScript';
import { MessageManager, MessageType, MessageUtils } from '../message';
import { LOG } from '../../../ConsoleLogCtrl';

// 确保可以访问全局 gc 对象
declare const gc: GameCore;

const { ccclass, property } = _decorator;

/**
 * 进度控制器
 * 负责处理进度条、播放控制按钮和回合控制按钮的逻辑
 */
@ccclass('ProgressController')
export class ProgressController extends Component {

    public sliderPlay: Slider;
    public labelCommand:Label;
    public labelRound:Label;
    public btnPlay: Button;
    public btnNext: Button;
    public btnNextRound: Button;
    public btnPre: Button;
    public btnPreRound: Button;
    public btnSpeed: Button;

    @property(Button)
    public btnStart: Button = null;

    /** 是否正在拖动进度条 */
    private _isDraggingSlider: boolean = false;

    /** 进度条更新定时器 */
    private _progressUpdateTimer: number = null;

    /** 命令管理器实例 */
    private _commandManager: CommandManager = null;

    /** 按钮点击防抖标志 */
    private _isButtonProcessing: boolean = false;

    /** 按钮点击防抖延时（毫秒） */
    private _buttonDebounceDelay: number = 300;

    /** 渲染回调函数 */
    private _renderCallback: () => void = null;

    /** 重置回调函数 */
    private _resetCallback: () => void = null;

    private manager: MessageManager = null;
    private uiManager: UIManager = null;
    private oldPlayProgress: number = 0;
    private speed: number = 1;

    /**
     * 组件加载时初始化
     */
    onLoad() {
        LOG.log('ProgressController onLoad: 初始化控制组件');
        this.initPanel();
        this.initManager();
        this.initOnClick();
        this.initPlaySlider();
        this.updateControlsVisibility();
        if (GameConfig.enableCommandSet || GameConfig.enableTestBattleScript) {
            this.initStartButton();
        }
    }

    public initPanel() {
        this.btnPlay = this.node.getChildByName('BtnPlay').getComponent(Button);
        this.btnNext = this.node.getChildByName('BtnNext').getComponent(Button);
        this.btnNextRound = this.node.getChildByName('BtnNextRound').getComponent(Button);
        this.btnPre = this.node.getChildByName('BtnPre').getComponent(Button);
        this.btnPreRound = this.node.getChildByName('BtnPreRound').getComponent(Button);
        this.btnSpeed = this.node.getChildByName('BtnSpeed').getComponent(Button);
        this.labelRound = this.node.getChildByName('LabelRound').getComponent(Label);
        this.labelCommand = this.node.getChildByName('LabelCommand').getComponent(Label);
        this.sliderPlay = this.node.getChildByName('SliderPlay').getComponent(Slider);
    }


    /**
     * 初始化按钮事件
     */
    public initOnClick() {
        this.btnPlay.node.on(Button.EventType.CLICK, this.onPlayButtonClick, this);
        this.btnNext.node.on(Button.EventType.CLICK, this.onNextButtonClick, this);
        this.btnNextRound.node.on(Button.EventType.CLICK, this.onNextRoundButtonClick, this);
        this.btnPre.node.on(Button.EventType.CLICK, this.onPreButtonClick, this);
        this.btnPreRound.node.on(Button.EventType.CLICK, this.onPreRoundButtonClick, this);
        this.btnStart.node.on(Button.EventType.CLICK, this.onStartButtonClick, this);
        this.btnSpeed.node.on(Button.EventType.CLICK, this.onSpeedButtonClick, this);

        const nextLabel = this.btnNext.node.getComponentInChildren(Label);
        nextLabel.string = '下一命令';
        const nextRoundLabel = this.btnNextRound.node.getComponentInChildren(Label);
        nextRoundLabel.string = '下一回合';
        const preLabel = this.btnPre.node.getComponentInChildren(Label);
        preLabel.string = '上一命令';
        const preRoundLabel = this.btnPreRound.node.getComponentInChildren(Label);
        preRoundLabel.string = '上一回合';
        this.updatePlayButtonText();
    }
    
    /**
     * 加速按钮点击事件
     */
    public onSpeedButtonClick() {
        if (this.speed < 3) {
            this.speed++;
        } else {
            this.speed = 1;
        }
        let _oldTick = director.tick;
        director.tick = (dt: number) => {
            _oldTick.call(director, dt * this.speed);
         }
        const speedLabel = this.btnSpeed.node.getComponentInChildren(Label);
        speedLabel.string = `x${this.speed}`;
    }

    /**
     * 设置渲染回调函数
     * @param callback 渲染回调函数
     */
    public setRenderCallback(callback: () => void) {
        this._renderCallback = callback;
    }

    /**
     * 设置重置回调函数
     * @param callback 重置回调函数
     */
    public setResetCallback(callback: () => void) {
        this._resetCallback = callback;
    }


    /**
     * 初始管理器
     */
    private initManager() {
        // 获取命令管理器单例
        this._commandManager = CommandManager.getInstance();
        this.manager = MessageManager.getInstance();
        this.uiManager = this.node.getParent().getComponent(UIManager);
    }

    /**
     * 初始化开始按钮
     */
    private initStartButton() {
        if (this.btnStart) {
            let startPanelNode = this.btnStart.node.getParent();
            startPanelNode.active = true;
            // 绑定按钮点击事件
            this.btnStart.node.on(Button.EventType.CLICK, this.onStartButtonClick, this);
            let node = this.btnStart.node.getParent().getChildByName("start");
            node.on(Node.EventType.TOUCH_END, this.onStartButtonClick, this);
            LOG.log('ProgressController: 播放按钮初始化完成');
        } else {
            LOG.warn('ProgressController: btnPlay 未设置，无法初始化播放按钮');
        }
    }

    /**
     * 初始化播放进度条
     */
    private initPlaySlider() {
        if (this.sliderPlay) {
            // 设置初始值
            this.sliderPlay.progress = 0;

            // 绑定事件
            let sliderPoint = this.sliderPlay.node.getChildByName('Handle');
            sliderPoint.on(Node.EventType.TOUCH_START, this.onSliderDragStart, this);
            sliderPoint.on(Node.EventType.TOUCH_END, this.onSliderDragEnd, this);
            sliderPoint.on(Node.EventType.TOUCH_CANCEL, this.onSliderDragEnd, this);
            LOG.log('ProgressController: 播放进度条初始化完成');
        } else {
            LOG.warn('ProgressController: sliderPlay 未设置，无法初始化播放进度条');
        }
    }

    /**
     * 开始定时更新进度条
     */
    public startProgressUpdate() {
        // 清除可能存在的旧定时器
        this.stopProgressUpdate();

        // 创建新的定时器，每50ms更新一次进度条
        this._progressUpdateTimer = setInterval(() => {
            this.updatePlaySlider();
        }, 50);

        LOG.log('ProgressController: 开始定时更新进度条');
    }

    /**
     * 停止定时更新进度条
     */
    public stopProgressUpdate() {
        if (this._progressUpdateTimer !== null) {
            clearInterval(this._progressUpdateTimer);
            this._progressUpdateTimer = null;
            LOG.log('ProgressController: 停止定时更新进度条');
        }
    }

    /**
     * 更新播放进度条
     */
    private updatePlaySlider() {
        if (!this.sliderPlay || !this._commandManager) {
            return;
        }

        const progress = this._commandManager.getPlayProgress();
        if (progress.total > 0) {
            this.sliderPlay.progress = progress.current / progress.total;
        } else {
            this.sliderPlay.progress = 0;
        }

        // 每次更新进度条时检查游戏是否结束，更新控制按钮和进度条的可见性
        this.updateControlsVisibility();

        if (this._commandManager.isGameEnded() && progress.current == progress.total) {
            this.pausePlayback();
            this.updatePlayButtonText();
            this.stopProgressUpdate();
        }
    }

    /**
     * 进度条拖动开始事件处理
     */
    private onSliderDragStart() {
        this._isDraggingSlider = true;
        LOG.log('ProgressController: 开始拖动进度条');

        // 立即暂停命令分发和所有动画
        this.pausePlayback();
        // 停止进度更新
        this.stopProgressUpdate();
    }

    /**
     * 进度条拖动结束事件处理
     */
    private onSliderDragEnd() {
        if (!this._commandManager || !this.sliderPlay) {
            this._isDraggingSlider = false;
            return;
        }

        // 记录拖拽开始前的播放状态
        const wasPlayingBeforeDrag = this._commandManager.getState() === CommandManagerState.PLAYING;

        // 计算目标位置
        const progress = this._commandManager.getPlayProgress();
        const targetPosition = Math.floor(this.sliderPlay.progress * progress.total);

        // 判断是否是后退操作
        if (targetPosition < progress.current) {
            LOG.log(`ProgressController: 检测到后退操作，将重置统计和日志`);
            this.reset();
        } else if (targetPosition == progress.current) {
            this._isDraggingSlider = false;
            return;
        }

        // 判断是否需要启用快进模式（后退或者快进超过5个命令）
        const shouldFastForward = targetPosition < progress.current || (targetPosition - progress.current) > 5;

        if (shouldFastForward) {
            // 启用快进模式，不渲染中间过程
            LOG.log(`ProgressController: 启用快进模式，目标位置: ${targetPosition}`);
            this._commandManager.setFastForwarding(true);
        }

        if (this._progressUpdateTimer === null) {
            this.startProgressUpdate();
        }

        // 设置播放位置并快速前进到该位置
        this._commandManager.setPlayPosition(targetPosition);
        this.uiManager.playerStatsCtrl.displayPlayerStats();

        // 如果启用了快进模式，现在需要渲染所有节点
        if (shouldFastForward && this._renderCallback) {
            LOG.log(`ProgressController: 快进完成，开始渲染所有节点`);
            // 确保命令管理器已经完成了位置设置
            setTimeout(() => {
                if (this._renderCallback) {
                    this._renderCallback();
                    LOG.log(`ProgressController: 节点渲染完成`);
                }
            }, 50); // 添加短暂延迟确保命令处理完成
            this._commandManager.setFastForwarding(false);
        }

        LOG.log(`ProgressController: 拖动进度条结束，设置位置到 ${targetPosition}/${progress.total}`);

        // 更新按钮文本
        this.updatePlayButtonText();
        this._isDraggingSlider = false;
        this.updatePlaySlider();

        // 根据拖拽前的播放状态决定是否恢复播放
        if (wasPlayingBeforeDrag) {
            this._commandManager.play();
            // 先强制刷新所有节点位置，确保位置同步
            if (this._renderCallback) {
                this._renderCallback();
            }
            // 然后恢复动画
            this.manager.sendMessage(MessageType.GAME_RESUME,{paused: false,});
            this.startProgressUpdate();
            LOG.log('ProgressController: 拖拽结束后恢复播放状态');
        } else {
            this.stopProgressUpdate();
        }
    }

    /**
     * 播放按钮点击事件处理
     */
    private onPlayButtonClick() {
        // 防止按钮快速点击
        if (this._isButtonProcessing) {
            LOG.log('ProgressController: 按钮点击过于频繁，忽略此次点击');
            return;
        }

        // 设置防抖标志
        this._isButtonProcessing = true;
                // 延时重置防抖标志
        setTimeout(() => {
            this._isButtonProcessing = false;
        }, this._buttonDebounceDelay);

        if (!this._commandManager) {
            LOG.error('CommandManager 未初始化，无法切换播放状态');
            return;
        }

        // 检查是否播放完成，如果完成则执行重播
        const progress = this._commandManager.getPlayProgress();
        if (progress.current >= progress.total && progress.total > 0) {
            this.onReplay();
            return;
        }

        const currentState = this._commandManager.getState();

        if (currentState === CommandManagerState.PLAYING) {
            // 当前是播放状态，切换到暂停
            this.pausePlayback();
            this.stopProgressUpdate();
            // 暂停统计面板的自动刷新
            this.pauseStatsPanelsAutoUpdate();
            LOG.log('ProgressController: 切换到暂停状态');

        } else {
            // 当前是暂停状态，切换到播放
            this.resumePlayback();
            this.startProgressUpdate();
            // 恢复统计面板的自动刷新
            this.resumeStatsPanelsAutoUpdate();
            LOG.log('ProgressController: 切换到播放状态');
        }

        // 更新按钮文本
        this.updatePlayButtonText();
        // 更新控制按钮的可见性
        this.updateControlsVisibility();

        // 显示状态变化消息
        if (this.uiManager) {
            const newState = this._commandManager.getState();
            const stateText = newState === CommandManagerState.PLAYING ? '播放' : '暂停';
            const progress = this._commandManager.getPlayProgress();
            this.uiManager.showMessage(`状态: ${stateText} | 回合: ${progress.currentRound}/${progress.totalRounds} | 命令: ${progress.current}/${progress.total}`);
            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 当前回合: ${progress.currentRound}, 总回合: ${progress.totalRounds}, 当前命令: ${progress.current}, 总命令: ${progress.total}`);
        }
    }

    /**
     * 下一命令按钮点击事件处理
     */
    private onNextButtonClick() {
        // 防止按钮快速点击
        if (this._isButtonProcessing) {
            LOG.log('ProgressController: 按钮点击过于频繁，忽略此次点击');
            return;
        }

        // 设置防抖标志
        this._isButtonProcessing = true;

        // 延时重置防抖标志
        setTimeout(() => {
            this._isButtonProcessing = false;
        }, this._buttonDebounceDelay);

        if (!this._commandManager) {
            LOG.error('CommandManager 未初始化，无法执行下一命令');
            return;
        }

        // 先暂停当前播放
        const wasPlaying = this._commandManager.getState() === CommandManagerState.PLAYING;
        if (wasPlaying) {
            this.pausePlayback();
        }

        // 获取当前播放进度
        const progress = this._commandManager.getPlayProgress();

        // 计算下一个命令的位置
        const nextPosition = progress.current + 1;

        // 如果已经是最后一个命令，则不执行操作
        if (nextPosition > progress.total) {
            if (this.uiManager) {
                this.uiManager.showMessage('已经是最后一个命令');
            }
            return;
        }

        // 设置到下一个命令的位置
        this._commandManager.setPlayPosition(nextPosition);

        // 主动更新进度条
        this.updatePlaySlider();

        LOG.log(`ProgressController: 播放下一命令，位置: ${nextPosition}/${progress.total}`);

        // 检查是否播放完成，如果完成则更新播放按钮为重播
        const updatedProgress = this._commandManager.getPlayProgress();
        if (this._commandManager.isGameEnded() && updatedProgress.current >= updatedProgress.total && updatedProgress.total > 0) {
            this.updatePlayButtonText();
            this.updateControlsVisibility();
        }

        // 显示消息
        if (this.uiManager) {
            this.uiManager.showMessage(`播放下一命令 | ${updatedProgress.currentRound}/${progress.totalRounds} 命令: ${updatedProgress.current}/${updatedProgress.total}`);

            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 当前回合: ${updatedProgress.currentRound}, 总回合: ${updatedProgress.totalRounds}, 当前命令: ${updatedProgress.current}, 总命令: ${updatedProgress.total}`);
        }

        if (wasPlaying) {
            this.resumePlayback();
            this.startProgressUpdate();
        }

        if (this._commandManager.getState() === CommandManagerState.PAUSED) {
            this.stopProgressUpdate();
        }
    }

    /**
     * 下一回合按钮点击事件处理
     */
    private onNextRoundButtonClick() {
        // 防止按钮快速点击
        if (this._isButtonProcessing) {
            LOG.log('ProgressController: 按钮点击过于频繁，忽略此次点击');
            return;
        }

        // 设置防抖标志
        this._isButtonProcessing = true;

        // 延时重置防抖标志
        setTimeout(() => {
            this._isButtonProcessing = false;
        }, this._buttonDebounceDelay);

        if (!this._commandManager) {
            LOG.error('CommandManager 未初始化，无法执行下一回合');
            return;
        }
       
        // 先暂停当前播放
        const wasPlaying = this._commandManager.getState() === CommandManagerState.PLAYING;
        if (wasPlaying) {
            this.pausePlayback();
        }

        // 获取当前播放进度和回合队列
        const progress = this._commandManager.getPlayProgress();
        const roundQueue = this._commandManager.getRoundQueue();
        // 获取当前回合索引
        const currentRoundIndex = progress.currentRound;

        // 计算下一个回合的第一个命令的位置
        let nextRoundPosition = 0;
        for (let i = 0; i < currentRoundIndex; i++) {
            nextRoundPosition += roundQueue[i].commands.length;
        }

        this._commandManager.setFastForwarding(true);

        // 设置到下一个回合的位置
        this._commandManager.setPlayPosition(nextRoundPosition);
        this.uiManager.playerStatsCtrl.displayPlayerStats();

        // 渲染所有节点
        if (this._renderCallback) {
            this._renderCallback();
        }
        this._commandManager.setFastForwarding(false);

        // 主动更新进度条
        this.updatePlaySlider();

        LOG.log(`ProgressController: 跳转到下一回合，位置: ${nextRoundPosition}/${progress.total}`);

        // 检查是否播放完成，如果完成则更新播放按钮为重播
        const updatedProgress = this._commandManager.getPlayProgress();
        if (this._commandManager.isGameEnded() && updatedProgress.current >= updatedProgress.total && updatedProgress.total > 0) {
            this.updatePlayButtonText();
            this.updateControlsVisibility();
        }

        // 显示消息
        if (this.uiManager) {
            this.uiManager.showMessage(`跳转下一回合 | ${updatedProgress.currentRound}/${updatedProgress.totalRounds} 命令: ${updatedProgress.current}/${updatedProgress.total}`);

            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 当前回合: ${updatedProgress.currentRound}, 总回合: ${updatedProgress.totalRounds}, 当前命令: ${updatedProgress.current}, 总命令: ${updatedProgress.total}`);
        }

        if (wasPlaying) {
            this.resumePlayback();
            this.startProgressUpdate();
        }

        if (this._commandManager.getState() === CommandManagerState.PAUSED) {
            this.stopProgressUpdate();
        }
    }

    /**
     * 上一命令按钮点击事件处理
     */
    private onPreButtonClick() {
        // 防止按钮快速点击
        if (this._isButtonProcessing) {
            LOG.log('ProgressController: 按钮点击过于频繁，忽略此次点击');
            return;
        }

        // 设置防抖标志
        this._isButtonProcessing = true;

        // 延时重置防抖标志
        setTimeout(() => {
            this._isButtonProcessing = false;
        }, this._buttonDebounceDelay);

        if (!this._commandManager) {
            LOG.error('CommandManager 未初始化，无法执行上一命令');
            return;
        }

        // 先暂停当前播放
        const wasPlaying = this._commandManager.getState() === CommandManagerState.PLAYING;
        if (wasPlaying) {
            this.pausePlayback();
        }

        // 获取当前播放进度
        const progress = this._commandManager.getPlayProgress();

        // 计算上一个命令的位置
        const prevPosition = progress.current - 1;

        // 如果已经是第一个命令，则不执行操作
        if (prevPosition < 0) {
            if (this.uiManager) {
                this.uiManager.showMessage('已经是第一个命令');
            }
            return;
        }

        // 从头开始渲染 相当于后退
        this.reset();

        this._commandManager.setFastForwarding(true);

        // 设置到上一个命令的位置
        this._commandManager.setPlayPosition(prevPosition);
        this.uiManager.playerStatsCtrl.displayPlayerStats();

        // 渲染所有节点
        if (this._renderCallback) {
            this._renderCallback();
        }
        this._commandManager.setFastForwarding(false);

        // 主动更新进度条
        this.updatePlaySlider();

        LOG.log(`ProgressController: 播放上一命令，位置: ${prevPosition}/${progress.total}`);

        // 显示消息
        if (this.uiManager) {
            // 获取更新后的进度
            const updatedProgress = this._commandManager.getPlayProgress();

            this.uiManager.showMessage(`播放上一命令 | ${updatedProgress.currentRound}/${updatedProgress.totalRounds} 命令: ${updatedProgress.current}/${updatedProgress.total}`);

            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 当前回合: ${updatedProgress.currentRound}, 总回合: ${updatedProgress.totalRounds}, 当前命令: ${updatedProgress.current}, 总命令: ${updatedProgress.total}`);
        }

        if (wasPlaying) {
            this.resumePlayback();
            this.startProgressUpdate();
        }

        if (this._commandManager.getState() === CommandManagerState.PAUSED) {
            this.stopProgressUpdate();
        }
    }

    /**
     * 上一回合按钮点击事件处理
     */
    private onPreRoundButtonClick() {
        // 防止按钮快速点击
        if (this._isButtonProcessing) {
            LOG.log('ProgressController: 按钮点击过于频繁，忽略此次点击');
            return;
        }

        if (!this._commandManager) {
            LOG.error('CommandManager 未初始化，无法执行上一回合');
            return;
        }

        // 设置防抖标志
        this._isButtonProcessing = true;

        // 延时重置防抖标志
        setTimeout(() => {
            this._isButtonProcessing = false;
        }, this._buttonDebounceDelay);

        // 先暂停当前播放
        const wasPlaying = this._commandManager.getState() === CommandManagerState.PLAYING;
        if (wasPlaying) {
            this.pausePlayback();
        }

        // 获取当前播放进度和回合队列
        const progress = this._commandManager.getPlayProgress();
        const roundQueue = this._commandManager.getRoundQueue();

        // 获取当前回合索引
        const currentRoundIndex = progress.currentRound;

        // 如果已经是第一个回合，则不执行操作
        if (currentRoundIndex <= 1) {
            if (this.uiManager) {
                this.uiManager.showMessage('已经是第一个回合');
            }
            return;
        }

        // 从头开始渲染 相当于后退
        this.reset();

        // 计算上一个回合的第一个命令的位置
        let prevRoundPosition = 0;
        for (let i = 0; i < currentRoundIndex - 2; i++) {
            prevRoundPosition += roundQueue[i].commands.length;
        }

        this._commandManager.setFastForwarding(true);

        // 设置到上一个回合的位置
        this._commandManager.setPlayPosition(prevRoundPosition);
        this.uiManager.playerStatsCtrl.displayPlayerStats();

        // 渲染所有节点
        if (this._renderCallback) {
            this._renderCallback();
        }
        this._commandManager.setFastForwarding(false);

        // 主动更新进度条
        this.updatePlaySlider();

        LOG.log(`ProgressController: 跳转到上一回合，位置: ${prevRoundPosition}/${progress.total}`);

        // 显示消息
        if (this.uiManager) {
            // 获取更新后的进度
            const updatedProgress = this._commandManager.getPlayProgress();

            this.uiManager.showMessage(`跳转上一回合 | ${updatedProgress.currentRound}/${updatedProgress.totalRounds} 命令: ${updatedProgress.current}/${updatedProgress.total}`);

            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 当前回合: ${updatedProgress.currentRound}, 总回合: ${updatedProgress.totalRounds}, 当前命令: ${updatedProgress.current}, 总命令: ${updatedProgress.total}`);
        }

        if (wasPlaying) {
            this.resumePlayback();
            this.startProgressUpdate();
        }

        if (this._commandManager.getState() === CommandManagerState.PAUSED) {
            this.stopProgressUpdate();
        }
    }

    /**
     * 开始游戏
     */
    public onStartButtonClick(){
        LOG.log('开始游戏');
        let node = this.btnStart.node.getParent();
        node.active = false;

        // 如果配置启用脚本或命令集测试
        if (GameConfig.enableCommandSet||GameConfig.enableTestBattleScript) {
            let commandExecutor = this.node.getComponent(CommandExecutor);
            if (!commandExecutor) {
                commandExecutor = this.node.addComponent(CommandExecutor);
            }

            // 如果启用TestBattleScript模式，确保添加TestBattleScript组件
            if (GameConfig.enableTestBattleScript) {
                let testBattleScript = this.node.getComponent(TestBattleScript);
                if (!testBattleScript) {
                    testBattleScript = this.node.addComponent(TestBattleScript);
                    LOG.log('已添加TestBattleScript组件');
                }
            }

            if (commandExecutor) {
                commandExecutor.startExecution();
            } else {
                LOG.error('CommandExecutor组件创建失败');
            }
        }

        // 恢复统计面板的自动刷新
        this._commandManager.play();
        this.resumeStatsPanelsAutoUpdate();
        this.startProgressUpdate();
        this.updateControlsVisibility();
    }


    /**
     * 重新开始播放
     */
    public onReplay() {
        LOG.log('ProgressController: 开始回放');

        // 重置战斗场景
        this.reset();

        // 通知UI管理器重播开始
        if (this.uiManager) {
            this.uiManager.onReplayStart();

            // 获取当前进度
            const progress = this._commandManager.getPlayProgress();

            this.uiManager.showMessage(`开始回放 | 当前回合: ${progress.currentRound}/${progress.totalRounds} | 当前命令: ${progress.current}/${progress.total}`);

            // 在控制台输出更详细的信息
            LOG.log(`ProgressController: 开始回放 - 当前回合: ${progress.currentRound}, 总回合: ${progress.totalRounds}, 当前命令: ${progress.current}, 总命令: ${progress.total}`);
        }

        this.resumePlayback();
        this.uiManager.playerStatsCtrl.displayPlayerStats();

        // 恢复统计面板的自动刷新
        this.resumeStatsPanelsAutoUpdate();

        // 更新按钮文本
        this.updatePlayButtonText();
        this.updateControlsVisibility();
        this.startProgressUpdate();
    }

    /**
     * 更新播放按钮的文本显示
     */
    private updatePlayButtonText() {
        if (!this.btnPlay || !this._commandManager) {
            return;
        }

        // 检查是否播放完成
        const progress = this._commandManager.getPlayProgress();
        const isCompleted = this._commandManager.isGameEnded() && progress.current >= progress.total && progress.total > 0;

        const currentState = this._commandManager.getState();
        const buttonLabel = this.btnPlay.node.getComponentInChildren(Label);

        if (buttonLabel) {
            if (isCompleted) {
                buttonLabel.string = '重播';
            } else if (currentState === CommandManagerState.PLAYING) {
                buttonLabel.string = '暂停';
            } else {
                buttonLabel.string = '播放';
            }
        } else {
            // 如果没有Label组件，尝试直接设置按钮的name作为显示
            if (isCompleted) {
                this.btnPlay.node.name = '重播';
            } else if (currentState === CommandManagerState.PLAYING) {
                this.btnPlay.node.name = '暂停';
            } else {
                this.btnPlay.node.name = '播放';
            }
        }
    }

    /**
     * 更新控制按钮和进度条的可见性
     */
    public updateControlsVisibility() {
        if (!this._commandManager) {
            return;
        }

        // 使用CommandManager的isGameEnded方法判断游戏是否已结束
        const isGameEnded = this._commandManager.isGameEnded();
        // 获取当前播放状态
        const isPlaying = this._commandManager.getState() === CommandManagerState.PLAYING;
        // 检查是否播放完成
        const progress = this._commandManager.getPlayProgress();
        const isCompleted = isGameEnded && progress.current >= progress.total && progress.total > 0;

        // 更新按钮和进度条的可见性
        if (this.btnPlay) {
            this.btnPlay.node.active = isGameEnded;
        }

        if (this.btnNext) {
            // 只有在游戏结束且不在播放状态时且未播放完成时才显示"下一命令"按钮
            this.btnNext.node.active = isGameEnded && !isPlaying && !isCompleted;
        }

        if (this.btnNextRound) {
            // 只有在游戏结束且不在播放状态时且未播放完成时才显示"下一回合"按钮
            this.btnNextRound.node.active = isGameEnded && !isPlaying && !isCompleted;
        }

        if (this.btnPre) {
            // 只有在游戏结束且不在播放状态时且未播放完成时才显示"上一命令"按钮
            this.btnPre.node.active = isGameEnded && !isPlaying && !isCompleted;
        }

        if (this.btnPreRound) {
            // 只有在游戏结束且不在播放状态时且未播放完成时才显示"上一回合"按钮
            this.btnPreRound.node.active = isGameEnded && !isPlaying && !isCompleted;
        }

        if (this.sliderPlay) {
            this.sliderPlay.node.active = isGameEnded;
            // 显示命令进度：（当前命令数/总命令数）
            this.labelCommand.string = `${progress.current}/${progress.total}`;
            this.labelCommand.node.active = isGameEnded;

            this.labelRound.string = `回合:${progress.currentRound}/${progress.totalRounds}`;
            this.labelRound.node.active = isGameEnded;
        }

        // 如果游戏刚刚结束，显示提示消息
        if (isGameEnded && this.uiManager && (!this.btnPlay.node.active || !this.sliderPlay.node.active)) {
            this.uiManager.showMessage('游戏已结束，可以使用播放控制查看回放');
        }
    }

    /**
     * 重置
     */
    public reset() {
        LOG.log('ProgressController: 开始重置');

        // 暂停统计面板的自动刷新
        this.pauseStatsPanelsAutoUpdate();

        // 调用重置回调函数
        if (this._resetCallback) {
            this._resetCallback();
        }

        // 重置命令管理器 - 重新开始播放但保留回合队列和统计数据
        if (this._commandManager) {
            this._commandManager.restartPlayback();
        }

        // 重置结算界面
        if(this.uiManager){
            this.uiManager.hideResultPanel();
            this.uiManager.clearUIManager();
        }

        // 重置播放控制UI
        this.updatePlayButtonText();
        this.updateControlsVisibility();
        if (this.sliderPlay) {
            this.sliderPlay.progress = 0;
        }

        LOG.log('ProgressController: 重置完成');
    }

    /**
     * 暂停回放
     */
    public pausePlayback() {
        if (this._commandManager) {
            this._commandManager.pause();
            this.manager.sendMessage(MessageType.GAME_PAUSE,{paused: true,});
        }
    }

    /**
     * 恢复回放
     */
    public resumePlayback() {
        if (this._commandManager) {
            this._commandManager.play();
            this.manager.sendMessage(MessageType.GAME_RESUME,{paused: false,});
        }
    }

    /**
     * 获取是否处于快进模式
     */
    public isFastForwarding(): boolean {
        return this._commandManager ? this._commandManager.isFastForwarding() : false;
    }

    /**
     * 暂停统计面板的自动刷新
     */
    private pauseStatsPanelsAutoUpdate() {
        if (this.uiManager) {
            if (this.uiManager.playerStatsCtrl) {
                this.uiManager.playerStatsCtrl.stopAutoUpdate();
            }
            if (this.uiManager.unitStatsCtrl) {
                this.uiManager.unitStatsCtrl.stopAutoUpdate();
            }
        }
    }

    /**
     * 恢复统计面板的自动刷新
     */
    private resumeStatsPanelsAutoUpdate() {
        if (this.uiManager) {
            if (this.uiManager.playerStatsCtrl) {
                this.uiManager.playerStatsCtrl.startAutoUpdate();
            }
            if (this.uiManager.unitStatsCtrl) {
                this.uiManager.unitStatsCtrl.startAutoUpdate();
            }
        }
    }

    /**
     * 组件销毁时清理资源
     */
    onDestroy() {
        // 清理按钮事件监听
        this.btnPlay.node.off(Button.EventType.CLICK, this.onPlayButtonClick, this);
        this.btnNext.node.off(Button.EventType.CLICK, this.onNextButtonClick, this);
        this.btnPre.node.off(Button.EventType.CLICK, this.onPreButtonClick, this);
        this.btnNextRound.node.off(Button.EventType.CLICK, this.onNextRoundButtonClick, this);
        this.btnPreRound.node.off(Button.EventType.CLICK, this.onPreRoundButtonClick, this);
        this.btnStart.node.off(Button.EventType.CLICK, this.onStartButtonClick, this);
        let sliderPoint = this.sliderPlay.node.getChildByName('Handle');
        if (sliderPoint) {
            sliderPoint.off(Node.EventType.TOUCH_START, this.onSliderDragStart, this);
            sliderPoint.off(Node.EventType.TOUCH_END, this.onSliderDragEnd, this);
            sliderPoint.off(Node.EventType.TOUCH_CANCEL, this.onSliderDragEnd, this);
        }

        // 停止定时更新
        this.stopProgressUpdate();
        LOG.log('ProgressController: 组件已销毁');
    }
}